import Vue from 'vue'
import ToastVue from './toast.vue'

const ToastConstructor = Vue.extend(ToastVue)
const instance = new ToastConstructor({
  el: document.createElement('div')
})

ToastConstructor.prototype.closeToast = () => {
  const el = instance.$el
  el.parentNode && el.parentNode.removeChild(el)
}

const Toast = (options = {}) => {
  let timer = null
  const timeout = ~~options.timeout || 2000
  const isString = typeof options === 'string'
  const close = () => {
    instance.closeToast()
    clearTimeout(timer)
  }

  instance.msg = isString ? options : options.msg
  instance.icon = options.icon
  instance.type = options.type
  instance.color = options.color
  instance.bgcolor = options.bgcolor

  document.body.appendChild(instance.$el)

  return new Promise(resolve => {
    instance.$on('closeToast', () => {
      resolve(close())
    })

    timer = setTimeout(() => {
      resolve(close())
    }, timeout + 100)
  })
}

export default Toast
